package com.ruoyi.quartz.race.type;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.quartz.race.model.RaceEntity;
import com.ruoyi.quartz.util.JedisUtil;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

/**
 * 获取所有赛事及当前赛季
 */
public class ServiceJc implements PageProcessor {
	private Site site = Site.me().setDomain("500.com").setSleepTime(10000)
			.setUserAgent(
					"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31")
			.addHeader("referer", "https://odds.500.com").addHeader("sec-fetch-dest", "empty")
			.addHeader("sec-fetch-mode", "cors").addHeader("sec-fetch-site", "same-origin")
			.addHeader("x-requested-with", "XMLHttpRequest");

	@Override
	public void process(Page page) {

		Selectable opts = page.getHtml().$("#sel_expect option");
		String dates = opts.$("option", "value").get();

		Selectable pds = page.getHtml().$("#table_match tr");
		List<Selectable> trs = pds.nodes();
		List<RaceEntity> resultList = new ArrayList();
		for (int i = 0; i < trs.size(); i++) {
			Selectable html = trs.get(i);
			String id = html.$("tr", "fid").get();
			if (id != null && !id.equals("")) {
				String gy = html.$("tr", "gy").get();
				String living = html.$("tr", "status").get();
				String[] gyarr = gy.split(",");
				String ctl1 = html.$(".clt1", "text").get();
				String ctl3 = html.$(".clt3", "text").get();
				List<Selectable> tds = html.$("td").nodes();
				String endtime = tds.get(3).$("td", "text").get();

				// String asa = AsUtilAppend.getHtml(id);
				// System.out.println(asa);
				String asa = tds.get(6).$("a").nodes().get(1).$("a", "text").get();

				RaceEntity rj = new RaceEntity();
				rj.setId(id);
				rj.setName(gyarr[0]);
				rj.setLname("[" + ctl1 + "]" + gyarr[1]);
				rj.setRname("[" + ctl3 + "]" + gyarr[2]);
				rj.setTime(endtime);
				rj.setAsian(asa);
				rj.setLiving(living);
				if (StringUtil.isNotEmpty(ctl1)) {
					rj.setLscore(Integer.parseInt(ctl1));
					rj.setRscore(Integer.parseInt(ctl3));
				}
				resultList.add(rj);
			}
		}

		// String nday = new
		// SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
		// if(nday.equals(dates)){
		JedisUtil.set("raceList:" + dates, JSON.toJSONString(resultList));
		// }
		System.out.println("----------------------------------------------");
	}

	@Override
	public Site getSite() {
		return site;
	}

	public static void main(String[] args) {
		Spider.create(new ServiceJc()).addUrl("https://live.500.com?e=2024-06-25").run();
	}
}
